package org.ihelpuoo.orm.filter;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.ihelpuoo.lang.StringUtils;
import org.ihelpuoo.orm.IIIException;

public abstract class SQLFilter implements Filter
{

	class OrderPair
	{
		OrderPair(String name, String order)
		{
			this.name = name;
			this.order = order;
		}

		String	name;
		String	order;
	}

	private List<OrderPair>		_orderby;

	public SQLFilter()
	{
		this._orderby = new LinkedList<OrderPair>();
	}

	public void addOrderBy(String name, String order)
	{
		this._orderby.add(new OrderPair(name,order));
	}

	public void clearOrders()
	{
		this._orderby.clear();
	}

	public String getString() throws IIIException
	{
		StringBuffer sb = new StringBuffer();
		CharSequence s = this.getConditionString();
		if (!StringUtils.isBlank(s))
			sb.append(" WHERE ").append(s);
		s = this.getOrderByString();
		if (!StringUtils.isBlank(s))
			sb.append(" ORDER BY ").append(s);

		if (sb.length() == 0)
			return "";
		return sb.toString();
	}

	public abstract CharSequence getConditionString() throws IIIException;

	public CharSequence getOrderByString()
	{
		if (_orderby.isEmpty())
			return null;
		StringBuffer sb = new StringBuffer();
		Iterator<OrderPair> it = this._orderby.iterator();
		OrderPair op = it.next();
		sb.append(op.name).append(' ').append(op.order);
		while (it.hasNext())
		{
			op = it.next();
			sb.append(',').append(op.name).append(' ').append(op.order);
		}
		return sb;
	}
}
